﻿using DotNetCore.CAP;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Servicecomb.Saga.Omega.Abstractions.Transaction;
using YDT_ProductService.Application.DTOs;
using YDT_ProductService.Application.Interfaces;
using YDT_ProductService.Monitors;

namespace YDT_ProductService.API.Controllers
{
    /// <summary>
    /// 商品控制器 - 处理商品相关的HTTP请求
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class ProductsController : ControllerBase
    {
        private readonly IProductService _productService;
        private readonly IConfiguration _configuration;
        private readonly ILogger<ProductsController> _logger;
        private readonly IServiceScopeFactory _scopeFactory;

        public ProductsController(IProductService productService, 
                                    IConfiguration configuration, 
                                    ILogger<ProductsController> logger, 
                                    IServiceScopeFactory scopeFactory)
        {
            _productService = productService;
            _configuration = configuration;
            _logger = logger;
            _scopeFactory = scopeFactory;
        }

        /// <summary>
        /// 获取所有商品
        /// </summary>
        /// <returns>商品列表</returns>
        [HttpGet]
        [DistributedResourceMointor("productservice", "getproducts")]
        [Authorize] // 使用分布式权限
        public async Task<ActionResult<IEnumerable<ProductDto>>> GetProducts()
        {
            // 使用配置中心
            string? AllowedHosts = _configuration["AllowedHosts"];

            // 使用日志中心
            _logger.LogInformation("查询商品成功.......");
            var products = await _productService.GetAllProductsAsync();
            return Ok(products);
        }

        /// <summary>
        /// 根据ID获取商品
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <returns>商品信息</returns>
        [HttpGet("{id:guid}")]
        public async Task<ActionResult<ProductDto>> GetProduct(Guid id)
        {
            var product = await _productService.GetProductByIdAsync(id);
            if (product == null)
            {
                return NotFound($"商品ID '{id}' 不存在");
            }
            return Ok(product);
        }

        /// <summary>
        /// 根据商品编码获取商品
        /// </summary>
        /// <param name="productCode">商品编码</param>
        /// <returns>商品信息</returns>
        [HttpGet("code/{productCode}")]
        public async Task<ActionResult<ProductDto>> GetProductByCode(string productCode)
        {
            var product = await _productService.GetProductByCodeAsync(productCode);
            if (product == null)
            {
                return NotFound($"商品编码 '{productCode}' 不存在");
            }
            return Ok(product);
        }

        /// <summary>
        /// 分页查询商品
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns>分页商品列表</returns>
        [HttpGet("paged")]
        public async Task<ActionResult> GetPagedProducts([FromQuery] ProductQueryDto query)
        {
            var (products, totalCount) = await _productService.GetPagedProductsAsync(query);
            return Ok(new { Products = products, TotalCount = totalCount });
        }

        /// <summary>
        /// 创建商品
        /// </summary>
        /// <param name="createProductDto">创建商品参数</param>
        /// <returns>创建的商品信息</returns>
        [HttpPost]
        [Compensable(nameof(DeleteProduct))] // 加入事务，并实现回滚
        public async Task<ActionResult<ProductDto>> CreateProduct(CreateProductDto createProductDto)
        {
            try
            {
                 var product = await _productService.CreateProductAsync(createProductDto);
                return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 回滚方法---> 相反操作！--->补偿操作
        /// </summary>
        /// <param name="createProductDto"></param>
        void DeleteProduct(CreateProductDto createProductDto)
        {
            //1、删除商品
            using (var scope = _scopeFactory.CreateScope())
            {
                IProductService productService = scope.ServiceProvider.GetRequiredService<IProductService>();
                _productService.DeleteProductAsync(createProductDto.Id).Wait();
                Console.WriteLine("删除商品成功");
            }
        }


        /// <summary>
        /// EventBus 创建商品
        /// </summary>
        /// <param name="createProductDto">创建商品参数</param>
        /// <returns>创建的商品信息</returns>
        [NonAction]
        [CapSubscribe("CreateProduct")]
        public async Task<ActionResult<ProductDto>> CreateProductByEventBusAsync(CreateProductDto createProductDto)
        {
            try
            {
                var product = await _productService.CreateProductAsync(createProductDto);
                return CreatedAtAction(nameof(GetProduct), new { id = product.Id }, product);
            }
            catch (ArgumentException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 更新商品
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <param name="updateProductDto">更新商品参数</param>
        /// <returns>更新后的商品信息</returns>
        [HttpPut("{id:guid}")]
        public async Task<ActionResult<ProductDto>> UpdateProduct(Guid id, UpdateProductDto updateProductDto)
        {
            var product = await _productService.UpdateProductAsync(id, updateProductDto);
            if (product == null)
            {
                return NotFound($"商品ID '{id}' 不存在");
            }
            return Ok(product);
        }

        /// <summary>
        /// 删除商品
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id:guid}")]
        public async Task<ActionResult> DeleteProduct(Guid id)
        {
            var result = await _productService.DeleteProductAsync(id);
            if (!result)
            {
                return NotFound($"商品ID '{id}' 不存在");
            }
            return NoContent();
        }

        /// <summary>
        /// 更新商品库存
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <param name="stock">库存数量</param>
        /// <returns>更新后的商品信息</returns>
        [HttpPatch("{id:guid}/stock")]
        public async Task<ActionResult<ProductDto>> UpdateStock(Guid id, [FromBody] int stock)
        {
            var product = await _productService.UpdateProductStockAsync(id, stock);
            if (product == null)
            {
                return NotFound($"商品ID '{id}' 不存在");
            }
            return Ok(product);
        }

        /// <summary>
        /// 增加商品库存
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <param name="quantity">增加数量</param>
        /// <returns>更新后的商品信息</returns>
        [HttpPatch("{id:guid}/stock/increase")]
        public async Task<ActionResult<ProductDto>> IncreaseStock(Guid id, [FromBody] int quantity)
        {
            var product = await _productService.IncreaseProductStockAsync(id, quantity);
            if (product == null)
            {
                return NotFound($"商品ID '{id}' 不存在");
            }
            return Ok(product);
        }

        /// <summary>
        /// 减少商品库存
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <param name="quantity">减少数量</param>
        /// <returns>更新后的商品信息</returns>
        [HttpPatch("{id:guid}/stock/decrease")]
        public async Task<ActionResult<ProductDto>> DecreaseStock(Guid id, [FromBody] int quantity)
        {
            try
            {
                var product = await _productService.DecreaseProductStockAsync(id, quantity);
                if (product == null)
                {
                    return NotFound($"商品ID '{id}' 不存在");
                }
                return Ok(product);
            }
            catch (InvalidOperationException ex)
            {
                return BadRequest(ex.Message);
            }
        }

        /// <summary>
        /// 增加商品销量
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <param name="quantity">销售数量</param>
        /// <returns>更新后的商品信息</returns>
        [HttpPatch("{id:guid}/sold/increase")]
        public async Task<ActionResult<ProductDto>> IncreaseSold(Guid id, [FromBody] int quantity)
        {
            var product = await _productService.IncreaseProductSoldAsync(id, quantity);
            if (product == null)
            {
                return NotFound($"商品ID '{id}' 不存在");
            }
            return Ok(product);
        }

        /// <summary>
        /// 激活商品
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <returns>更新后的商品信息</returns>
        [HttpPatch("{id:guid}/activate")]
        public async Task<ActionResult<ProductDto>> ActivateProduct(Guid id)
        {
            var product = await _productService.ActivateProductAsync(id);
            if (product == null)
            {
                return NotFound($"商品ID '{id}' 不存在");
            }
            return Ok(product);
        }

        /// <summary>
        /// 禁用商品
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <returns>更新后的商品信息</returns>
        [HttpPatch("{id:guid}/deactivate")]
        public async Task<ActionResult<ProductDto>> DeactivateProduct(Guid id)
        {
            var product = await _productService.DeactivateProductAsync(id);
            if (product == null)
            {
                return NotFound($"商品ID '{id}' 不存在");
            }
            return Ok(product);
        }

        /// <summary>
        /// 添加商品图片
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <param name="imageDto">商品图片参数</param>
        /// <returns>更新后的商品信息</returns>
        [HttpPost("{id:guid}/images")]
        public async Task<ActionResult<ProductDto>> AddProductImage(Guid id, CreateProductImageDto imageDto)
        {
            var product = await _productService.AddProductImageAsync(id, imageDto);
            if (product == null)
            {
                return NotFound($"商品ID '{id}' 不存在");
            }
            return Ok(product);
        }

        /// <summary>
        /// 移除商品图片
        /// </summary>
        /// <param name="id">商品ID</param>
        /// <param name="imageId">图片ID</param>
        /// <returns>更新后的商品信息</returns>
        [HttpDelete("{id:guid}/images/{imageId:guid}")]
        public async Task<ActionResult<ProductDto>> RemoveProductImage(Guid id, Guid imageId)
        {
            var product = await _productService.RemoveProductImageAsync(id, imageId);
            if (product == null)
            {
                return NotFound($"商品ID '{id}' 或图片ID '{imageId}' 不存在");
            }
            return Ok(product);
        }
    }
}
